<?php
class AuthService extends Service{
    
    /**
     * @param object $data
     * <pre>
     * {
     *   "type":"object",
     *   "properties": {
     *     "name":{"type":"string"},
     *     "password":{"type":"string"}
     *   }
     * }
     * </pre>
     * @return void
     */
    static function login($data) {
        $dbUser = UserTable::findWithRolesAndPermissions(null, $data->name);
        if($dbUser && $dbUser['password'] == $data->password) {
            $user = sfContext::getInstance()->getUser();
            $arPermissions = self::extractArPermissions($dbUser);
            //Dbg::x($arPermissions);
            $user->addCredentials($arPermissions);
            $user->setAttribute('id',$dbUser['id']);
            $user->setAttribute('name',$dbUser['name']);
            $user->setAuthenticated(true);
        }
        else {
            throw new InvalidUserAndPasswordException();
        }
    }

    static function extractArPermissions($dbUser) {
        $arPermissions = array();
        foreach($dbUser['GeneralRole'] as $role) {
            foreach($role['Permission'] as $permission) {
                $arPermissions[] = $permission['name'];
            }
        }
        if(array_key_exists('UserProjectRole',$dbUser)) {
            foreach($dbUser['UserProjectRole'] as $upr) {
                $role = $upr['Role'];
                foreach($role['Permission'] as $permission) {
                    $arPermissions[] = $permission['name'];
                }
            }
        }
        return $arPermissions;
    }



    static function logout() {
        $user = sfContext::getInstance()->getUser();
        $user->setAuthenticated(false);
        $user->getAttributeHolder()->clear();
        $user->clearCredentials();
    }

    static function setProject($projectId) {
        $project = ProjectsService::get($projectId);
        $user = sfContext::getInstance()->getUser();
        $user->setAttribute('projectId', $projectId);
        $user->setAttribute('projectName', $project['name']);
        //get project credentials.
        $dbUser = UserTable::findWithRolesAndPermissions($user->getAttribute('id'),null,$projectId);
        $user->addCredentials(self::extractArPermissions($dbUser));
    }

    static function unsetProject() {
        $user = sfContext::getInstance()->getUser();
        $user->getAttributeHolder()->remove('projectId');
        $user->getAttributeHolder()->remove('projectName');
        //get project credentials.
        $dbUser = UserTable::findWithRolesAndPermissions($user->getAttribute('id'));
        $user->clearCredentials();
        $user->addCredentials(self::extractArPermissions($dbUser));
    }
}

?>
